package com.kedacom.demo.utils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.kedacom.demo.Constants;

/**
 * StringSerializer
 * @author luocanfeng
 * @date 2015年9月8日
 */
public class StringSerializer {

	private static Charset charset = Constants.CHARSET_UTF8;

	public static byte[] toByteArray(String str) {
		return str == null ? null : str.getBytes(charset);
	}

	public static String fromByteArray(byte[] bytes) {
		return bytes == null ? null : new String(bytes, charset);
	}

	public static String[] fromBytesArray(byte[]... arr) {
		String[] result = new String[arr.length];
		for (int i = 0; i < arr.length; i++) {
			result[i] = fromByteArray(arr[i]);
		}
		return result;
	}

	public static byte[][] toBytesArray(String... arr) {
		byte[][] result = new byte[arr.length][];
		for (int i = 0; i < arr.length; i++) {
			result[i] = toByteArray(arr[i]);
		}
		return result;
	}

	public static List<String> fromBytesList(List<byte[]> list) {
		List<String> result = new ArrayList<String>();
		for (byte[] bytes : list) {
			result.add(fromByteArray(bytes));
		}
		return result;
	}

	public static Set<String> fromBytesSet(Set<byte[]> set) {
		Set<String> result = new LinkedHashSet<String>();
		for (byte[] bytes : set) {
			result.add(fromByteArray(bytes));
		}
		return result;
	}

	public static Map<byte[], byte[]> toByteMap(Map<String, String> map) {
		Map<byte[], byte[]> result = new LinkedHashMap<byte[], byte[]>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			result.put(StringSerializer.toByteArray(entry.getKey()), StringSerializer.toByteArray(entry.getValue()));
		}
		return result;
	}

	public static Map<String, String> fromByteMap(Map<byte[], byte[]> map) {
		Map<String, String> result = new LinkedHashMap<String, String>();
		for (Map.Entry<byte[], byte[]> entry : map.entrySet()) {
			result.put(StringSerializer.fromByteArray(entry.getKey()), StringSerializer.fromByteArray(entry.getValue()));
		}
		return result;
	}

}
